//
//  LoansNewsViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/10/22.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import XLPagerTabStrip

@objc protocol LoansNewsDelegate {
    @objc optional func changeScrollHeight(height:CGFloat) //改变滑动高度
    @objc optional func updateTitle() //刷新标题
}

class LoansNewsViewController: KMViewController,IndicatorInfoProvider {
    
    weak var delegate : LoansNewsDelegate?

    fileprivate let cellId = "loansNewsCell"
    
    var dataArray = [NewsModel]()
    
    var itemInfo:IndicatorInfo = ""
    
    var urlString  = ""
    
    var page = 1
    
    fileprivate var tableView : UITableView!
    
    init(urlString:String) {
        super.init(nibName: nil, bundle: nil)
        
        self.urlString = webUrl + "/mobile/mores/i" + urlString
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        createTableView()
        
        
        KMTool.setRefresh(with: self.tableView, headerAction: {[weak self] in
            
            self?.page = 1
            self?.getData(url: (self?.urlString)!)
            
            
        }) {[weak self] in
            
            if (self?.tableView.mj_header.isRefreshing)! {
                self?.tableView.mj_footer.endRefreshing()
                return
            }
            
            self?.getData(url: (self?.urlString)! + "_p\(self!.page)")
            
        }
        
        self.getData(url: self.urlString)
        
    }
    
    //MARK: 创建tableView
    fileprivate func createTableView() {
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.clear
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(NewsCell.self, forCellReuseIdentifier: cellId)
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
    }
    
    //MARK: 获取数据
    fileprivate func getData(url:String) {
        
        self.delegate?.updateTitle!()
        
        KMTool.requestGetData(URLString: url, parameters: nil,  success: { (data) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            let elements = ["//ul[@id='content']/section/li/a","//ul[@id='content']/section/li/a/img","//ul[@id='content']/section/li/a/div[@class='content']/span[@class='span_top']","//ul[@id='content']/section/li/a/div[@class='content']/small"]
            let attributes = ["href","src","text","text"]
            let keys = ["href","image","title","time"]
            
            let array = KMTool.htmlToModel(data: data, elements: elements, attributes: attributes, keys: keys)
            
            if array.count == 0 {
                return
            }else{
                if self.page == 1 {
                    self.dataArray.removeAll()
                }
                self.page += 1
            }
            
            for item in array {
                let model = NewsModel.setModel(with: item)
                self.dataArray.append(model)
            }
            
            self.tableView.reloadData()
        }) {
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
        
        return itemInfo
    }
    
    

    

}


extension LoansNewsViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return RATIO_H(maxNum: 100)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? NewsCell
        cell?.model = dataArray[indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let model = dataArray[indexPath.row]
        let webVC = WebViewController.init(urlString: kmHttps + model.href!, title: self.itemInfo.title, shareImage: kmHttps + model.image!, shareText: model.text,shareTitle:model.title)
        webVC.removeElements = ["mblocks","crumbs mblock","mfooter mblock footer1"]
        webVC.removeIds = ["xiong_div"]
        webVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(webVC, animated: true)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        self.delegate?.changeScrollHeight!(height: scrollView.contentOffset.y)
    }
    
}



